<template>
    <div>
        <div class="content-div">
            <Row style="margin-top:10px">
                <Col span="15" class="table-form-input-select-col">
                <span class="alltitle" style="line-height:30px"><router-link to="项目列表"> 项目列表</router-link>>校招职位</span>
                </Col>
                <Col span="3">
                <span class="inline-title"> <a href="../51admin/example2.xlsx">
                      下载职位表格模板
                    </a></span>
                </Col>
                <Col span="2">
                <span class="inline-title" @click="handleFileChange">批量导入</span>
                <form id="activeForm" enctype="multipart/form-data">
                    <input type="file" id="fileExport" ref="inputer" style="display:none" @change="importExcel($event)" name="file[]">
                </form>
                </Col>
                <Col span="2">
                  <span class="inline-title" @click="sync">会员号同步</span>
                </Col>
                <Col span="2">
                  <span class="inline-title" @click="sync2">{{hasInternalTask ? '停止自动同步' : '自动同步'}}</span>
                </Col>
            </Row>
            <Row style="margin-top:10px">
                <Col span="2">
                    <Button type="primary" size="large" @click="addNewJob">新增职位</Button>
                </Col>
                <Col span="4" offset="7">
                    <span style="font-weight: bold;font-size: 16px">小程序筛选条件开关：</span>
                </Col>
                <Col span="2">
                    <span>工作地点（城市）</span><br/>
                    <i-switch v-model="jobsel.jobsel_1" :true-value="'1'" :false-value="'0'">
                        <span slot="open">开</span>
                        <span slot="close">关</span>
                    </i-switch>
                </Col>
                <Col span="2">
                    <span>职能</span><br/>
                    <i-switch v-model="jobsel.jobsel_2" :true-value="'1'" :false-value="'0'">
                        <span slot="open">开</span>
                        <span slot="close">关</span>
                    </i-switch>
                </Col>
                <Col span="2">
                    <span>部门（分公司）</span><br/>
                    <i-switch v-model="jobsel.jobsel_3" :true-value="'1'" :false-value="'0'">
                        <span slot="open">开</span>
                        <span slot="close">关</span>
                    </i-switch>
                </Col>
                <Col span="3">
                    <span>类别</span><br/>
                    <i-switch v-model="jobsel.jobsel_4" :true-value="'1'" :false-value="'0'">
                        <span slot="open">开</span>
                        <span slot="close">关</span>
                    </i-switch>
                </Col>
                <Col span="2">
                    <Button type="info" @click="saveJobSel">保存条件</Button>
                </Col>
            </Row>
        </div>
        <div class="content-div" style="margin-top:20px">
            <Table border stripe :columns="columns2" :data="data" ref="table"></Table>
        </div>
        <div class="content-div" align="center">
            <Page @on-change="changepage" :total="pageData.total" :current="pageData.current" :page-size="pageData.pageSize" style="padding:5px 5px 2px 5px;" show-elevator></Page>
        </div>
        <Modal class="modelEdit" v-model="addJobModel1" width="900" :mask-closable="false" title="编辑职位" @on-ok="okEdit('formData')">
            <Form ref="formData" :model="editDataModalObject" :rules="ruleformData" inline>
                <FormItem label="职位名称" :label-width="100" prop="jobname">
                    <Input class="input-item" placeholder="输入职位名称" v-model="editDataModalObject.jobname"></Input>
                </FormItem>
                <FormItem label="工作地点" :label-width="100" class="formitem" prop="jobareaname">
                    <Input class="input-item2" placeholder="输入工作地点" v-model="editDataModalObject.jobareaname"></Input>
                </FormItem>
                <FormItem label="部门" :label-width="100" prop="divname">
                    <Input class="input-item" placeholder="输入部门" v-model="editDataModalObject.divname"></Input>
                </FormItem>
                <FormItem label="类别" :label-width="100" class="formitem" prop="jobtype">
                    <Input class="input-item2" placeholder="输入类别" v-model="editDataModalObject.jobtype"></Input>
                </FormItem>
                <FormItem label="学历要求" :label-width="100" prop="degreefrom">
                    <Input class="input-item" placeholder="输入学历要求" v-model="editDataModalObject.degreefrom"></Input>
                </FormItem>
                <FormItem label="招聘人数" :label-width="100" class="formitem" prop="jobnum">
                    <Input class="input-item2" placeholder="输入招聘人数" v-model="editDataModalObject.jobnum"></Input>
                </FormItem>
                <FormItem label="发布时间" :label-width="100" prop="issuedate">
                    <Input class="input-item" placeholder="输入发布时间" v-model="editDataModalObject.issuedate"></Input>
                </FormItem>
                <FormItem label="职能类别" :label-width="100" class="formitem" prop="funtype">
                    <Input class="input-item2" placeholder="输入职能类别" v-model="editDataModalObject.funtype"></Input>
                </FormItem>
                <FormItem label="职位ID" :label-width="100" prop="url">
                    <Input placeholder="输入职位ID" v-model="editDataModalObject.url" style="width:700px;margin-left:45px"></Input>
                </FormItem>
                <FormItem label="职位详情" :label-width="100" prop="content">
                    <Input :rows="9" type="textarea" placeholder="输入职位详情" v-model="editDataModalObject.content" style="width:700px;margin-left:45px"></Input>
                </FormItem>
            </Form>
        </Modal>
        <Modal class="modelEdit" v-model="addJobModel2" width="900" :mask-closable="false" title="新增职位" @on-ok="okAdd('formData2')">
            <Form ref="formData2" :model="formData2" :rules="ruleformData2" inline>
                <FormItem label="职位名称" :label-width="100" prop="jobname">
                    <Input class="input-item" placeholder="输入职位名称" v-model="formData2.jobname"></Input>
                </FormItem>
                <FormItem label="工作地点" :label-width="100" class="formitem" prop="jobareaname">
                    <Input class="input-item2" placeholder="输入工作地点" v-model="formData2.jobareaname"></Input>
                </FormItem>
                <FormItem label="部门" :label-width="100" prop="divname">
                    <Input class="input-item" placeholder="输入部门" v-model="formData2.divname"></Input>
                </FormItem>
                <FormItem label="类别" :label-width="100" class="formitem" prop="jobtype">
                    <Input class="input-item2" placeholder="输入类别" v-model="formData2.jobtype"></Input>
                </FormItem>
                <FormItem label="学历要求" :label-width="100" prop="degreefrom">
                    <Input class="input-item" placeholder="输入学历要求" v-model="formData2.degreefrom"></Input>
                </FormItem>
                <FormItem label="招聘人数" :label-width="100" class="formitem" prop="jobnum">
                    <Input class="input-item2" placeholder="输入招聘人数" v-model="formData2.jobnum"></Input>
                </FormItem>
                <FormItem label="发布时间" :label-width="100" prop="issuedate">
                    <Input class="input-item" placeholder="输入发布时间" v-model="formData2.issuedate"></Input>
                </FormItem>
                <FormItem label="职能类别" :label-width="100" class="formitem" prop="funtype">
                    <Input class="input-item2" placeholder="输入职能类别" v-model="formData2.funtype"></Input>
                </FormItem>
                <FormItem label="职位ID" :label-width="100" prop="url">
                    <Input placeholder="输入职位ID" v-model="formData2.url" style="width:700px;margin-left:45px"></Input>
                </FormItem>
                <FormItem label="职位详情" :label-width="100" prop="content">
                    <Input :rows="9" type="textarea" placeholder="输入职位详情" v-model="formData2.content" style="width:700px;margin-left:45px"></Input>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
export default {
    data() {
            return {
                category: 1,
                jobinfo: [{
                    value: "",

                }],
                jobsel: {
                    jobsel_1: '0',
                    jobsel_2: '0',
                    jobsel_3: '0',
                    jobsel_4: '0',
                },
                pageData: {
                    current: 1,
                    total: 1,
                    pageSize: 20
                },
                addJobModel1: false,
                addJobModel2: false,
                formData: {
                    id: "",
                    jobname: "",
                    jobareaname: "",
                    degreefrom: "",
                    jobnum: "",
                    issuedate: "",
                    funtype: "",
                    url: "",
                    content: "",
                    divname: "",
                    jobtype: ""
                },
                ruleformData: {
                    jobname: [{
                        required: true,
                        message: "请输入职位名称",
                        trigger: "change"
                    }],
                    issuedate: [{
                        required: true,
                        message: "请输入发布日期",
                        trigger: "change"
                    }],
                    jobareaname: [{
                        required: true,
                        message: "请输入工作地点",
                        trigger: "change"
                    }],
                    degreefrom: [{
                        required: true,
                        message: "请输入学历要求",
                        trigger: "change"
                    }],
                    jobnum: [{
                        required: true,
                        message: "请输入招聘人数",
                        trigger: "change"
                    }],
                    funtype: [{
                        required: true,
                        type: "string",
                        message: "请输入职能类型",
                        trigger: "change"
                    }],
                    url: [{
                        required: true,
                        type: "string",
                        message: "请输入职位ID",
                        trigger: "change"
                    }],
                    content: [{
                        required: true,
                        message: "请输入职位详情",
                        trigger: "change"
                    }],
                    divname: [{
                        required: false,
                        message: "请输入部门",
                        trigger: "change"
                    }],
                    jobtype: [{
                        required: true,
                        message: "请输入职位类型",
                        trigger: "change"
                    }]
                },
                ruleformData2: {
                    jobname: [{
                        required: true,
                        message: "请输入职位名称",
                        trigger: "change"
                    }],
                    issuedate: [{
                        required: true,
                        message: "请输入发布日期",
                        trigger: "change"
                    }],
                    jobareaname: [{
                        required: true,
                        message: "请输入工作地点",
                        trigger: "change"
                    }],
                    degreefrom: [{
                        required: true,
                        message: "请输入学历要求",
                        trigger: "change"
                    }],
                    jobnum: [{
                        required: true,
                        message: "请输入招聘人数",
                        trigger: "change"
                    }],
                    funtype: [{
                        required: true,
                        type: "string",
                        message: "请输入职能类型",
                        trigger: "change"
                    }],
                    url: [{
                        required: true,
                        type: "string",
                        message: "请输入职位ID",
                        trigger: "change"
                    }],
                    content: [{
                        required: true,
                        message: "请输入职位详情",
                        trigger: "change"
                    }],
                    divname: [{
                        required: false,
                        message: "请输入部门",
                        trigger: "change"
                    }],
                    jobtype: [{
                        required: true,
                        message: "请输入职位类型",
                        trigger: "change"
                    }]
                },
                formData2: {
                    id: "",
                    jobname: "",
                    jobareaname: "",
                    degreefrom: "",
                    jobnum: "",
                    issuedate: "",
                    funtype: "",
                    url: "",
                    content: "",
                    divname: "",
                    jobtype: ""
                },
                hasInternalTask: false,
                columns2: [{
                    title: "序号",
                    key: "id",
                    width: 99,

                }, {
                    title: "职位名称",
                    key: "jobname",

                }, {
                    title: "工作地点",
                    key: "jobareaname",

                }, {
                    title: "部门",
                    key: "divname",

                }, {
                    title: "类别",
                    key: "jobtype",

                }, {
                    title: "学历要求",
                    key: "degreefrom",
                    width: 150,

                }, {
                    title: "招聘人数",
                    key: "jobnum",
                    width: 150,

                }, {
                    title: "发布时间",
                    key: "issuedate",
                    width: 150,

                }, {
                    title: "职能类型",
                    key: "funtype",
                    width: 150,

                }, {
                    title: "操作",
                    key: "action",
                    width: 99,

                    render: (h, params) => {
                        return h("div", [
                            h(
                                "span", {
                                    style: {
                                        textDecoration: "underline",
                                        color: "#4b80fd",
                                        cursor: "pointer"
                                    },
                                    on: {
                                        click: () => {
                                            this.show(params.index);
                                        }
                                    }
                                },
                                "编辑"
                            ),
                            h(
                                "span", {
                                    style: {
                                        textDecoration: "underline",
                                        color: "#4b80fd",
                                        cursor: "pointer",
                                        'margin-left': "5px",
                                    },
                                    on: {
                                        click: () => {
                                            this.removeData(params.index);
                                        }
                                    }
                                },
                                "删除"
                            )
                        ]);
                    }
                }],
                data: [],
                editDataModalObject: {},
            };
        },
        methods: {
            removeData(index) {
                var self = this
                self.$Modal.confirm({
                    title: '确认删除？',
                    content: '',
                    onOk: () => {

                        var self = this;
                        self.$api.post('/api/v1/edit', self.data[index], function(result) {
                            self.data.splice(index, 1)
                            self.$Message.info(result.message)
                        })


                        $.ajax({
                            url: "https://evp.51job.com/51job/api/51miniadmin/back.php?action=jobdel&id=" + self.data[index].id,

                            type: "POST",
                            dataType: "json",
                            success: function(data) {

                                console.log(data);

                            }
                        });
                    },
                    onCancel: () => {
                        this.$Message.info('取消删除');
                    }
                });

            },
            saveJobSel() {
                var self = this
                var poid = localStorage.pid;
                $.ajax({
                    url: "https://evp.51job.com/51job/api/51miniadmin/back.php?action=saveJobSelection&id=" + poid,
                    data: {
                        'jobsel_1': self.jobsel.jobsel_1,
                        'jobsel_2': self.jobsel.jobsel_2,
                        'jobsel_3': self.jobsel.jobsel_3,
                        'jobsel_4': self.jobsel.jobsel_4,
                    },
                    type: "POST",
                    dataType: "json",
                    success: function(result) {
                        console.log(result.code);
                        if (result.code == 1) {
                            self.$Message.success('保存成功');
                        } else {
                            self.$Message.error('保存失败');
                        }
                    }
                });
            },
            endTask() {
              const poid = localStorage.pid;
              this.$Modal.confirm({
                title: '自动同步',
                content: '确定停止定时同步?',
                onOk: () => {
                  $.post('https://evp.51job.com/51job/api/1.0/index.php/mini_xy/shell/killProject', {
                    project_id: poid
                  }).then(res => {
                    if(res.code === 1) {
                      this.hasInternalTask = false;
                      this.$Notice.success({
                        title: '自动同步',
                        desc: '已关闭自动同步',
                        duration: 2
                      })
                    } else {
                      this.$Notice.error({
                        title: '自动同步',
                        desc: '关闭自动同步失败: ' + res.msg,
                        duration: 3
                      })
                    }
                  })
                }
              })
            },
            sync2() {
                if(this.hasInternalTask) { this.endTask();return; }

                this.$Modal.confirm({
                    render: (h) => {
                        return h('Input', {
                            props: {
                                value: this.value,
                                autofocus: true,
                                placeholder: '请输入会员号'
                            },
                            on: {
                                input: (val) => {
                                    this.value = val;
                                }
                            }
                        })
                    },
                    onOk: () => {
                      // 获取会员号
                      const ctmid = this.value
                      // 获取projid
                      const poid = localStorage.pid;
                      // 发送接口
                      $.post('https://evp.51job.com/51job/api/1.0/index.php/mini_xy/shell/execProject', {
                        project_id: poid,
                        ctm_id: ctmid
                      }).then(res => {
                        if(res.code === 1) {
                          this.hasInternalTask = true;
                          this.$Notice.success({
                            title: '自动同步',
                            desc: `自动同步设置完成! 系统会在每天凌晨2点自动同步,请确认以下信息:<br>会员号: ${ctmid}<br>项目id: ${poid}`,
                            duration: 0
                          })
                        } else {
                          this.$Notice.error({
                            title: '自动同步',
                            desc: '自动同步设置失败: ' + res.msg,
                            duration: 3
                          })
                        }
                      });
                    },
                })
            },
            sync() {

                this.$Modal.confirm({
                    render: (h) => {
                        return h('Input', {
                            props: {
                                value: this.value,
                                autofocus: true,
                                placeholder: '输入会员号,以英文逗号分隔'
                            },
                            on: {
                                input: (val) => {
                                    this.value = val;

                                }
                            }
                        })
                    },
                    onOk: () => {
                        var self = this

                        var poid = localStorage.pid;
                        // 新增多会员号支持：
                        var ctmidList = this.value.split(',');
                        // /\d/g.test('')  // 检查是否是数字的正则
                        
                        // 递归获取
                        function getJobList(ctmidList, finish) {
                            function _get(ctmidList, page, totalList, finish) {
                              coapi.getJobList({ ctmid: ctmidList[0], pagesize: 1000, pagenum: page }, function (res) {
                                if (res.status == 1 && res.resultbody.joblist && res.resultbody.joblist.length > 0) {
                                  _get(ctmidList, page + 1, totalList.concat(res.resultbody.joblist), finish)
                                } else if(ctmidList.length > 1) {
                                  _get(ctmidList.slice(1), 1, totalList, finish)
                                }  else{
                                    finish(totalList);
                                }
                              })
                            }
                            _get(ctmidList, 1, [], finish)
                        }
                        // 调用
                        getJobList(ctmidList, list => {
                            // post接口写在这里
                            try {
                                if(list.length > 0) {
                                    $.ajax({
                                        url: `https://evp.51job.com/51job/api/51miniadmin/back.php?action=jobsync&id=${poid}&category=${this.category}`,
                                        data: {
                                            'data': JSON.stringify(list)
                                        },
                                        type: "POST",
                                        dataType: "json",
                                        success: function(result) {
                                            console.log(result.code);
                                            if (result.code == 1) {
                                                self.$Message.success('同步成功');
                                                self.changepage(1);
                                            } else {
                                                self.$Message.error('同步失败');
                                            }
                                        }
                                    });
                                } else {
                                    self.$Message.error('该号下没有职位');
                                }
                                
                            } catch (error) {
                                console.log(error, list)
                            }
                        })
                    },
                })
            },
            importExcel() {
                var poid = localStorage.pid;
                var self = this;
                var formData = new FormData($("#activeForm")[0]);

                $.ajax({
                    url: `https://evp.51job.com/51job/api/51miniadmin/back.php?action=jobbatch&id=${poid}&category=${this.category}`,
                    data: formData,
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: "POST",
                    dataType: "json",

                    success: function(data) {

                        console.log(data);
                        var iRepeat = data.iRepeat
                        var iSuccess = data.iSuccess

                        if (data.code == 1) {

                            self.$Message.success('导入完成' + iSuccess + '条,重复的有' + iRepeat + '条');
                            self.changepage(1);

                        } else {

                            self.$Message.error('导入失败');

                        }

                    }
                });

            },
            handleFileChange() {

                $("#fileExport").click();

            },

            changepage(currentPage) {
                if (isNaN(currentPage)) {
                    currentPage = 1
                }
                var self = this
                    /*self.$api.get('/api/v1/table_data', null, function (result) {
                      self.data = result.resultData.dataList
                      self.pageData = result.resultData.pageData
                    })*/
                var searchdata = {};

                console.log(searchdata)

                var poid = localStorage.pid;
                $.ajax({
                    url: "https://evp.51job.com/51job/api/51miniadmin/back.php?action=joblist&pagesize=20&id=" 
                          + poid + "&pageindex=" + currentPage + '&category=' + this.category,
                    type: "POST",
                    dataType: "json",
                    success: function(data) {

                        console.log(data);

                        if (data.data != null) {

                            self.data = data.data
                            self.pageData.total = parseInt(data.datatotal)
                            self.pageData.pageSize = 20
                            self.current = currentPage

                        } else {

                            self.$Message.error('没有职位');

                        }

                    }
                });
            },
            show(index) {
                this.addJobModel1 = true;

                this.editDataModalObject = this.data[index];
                console.log(this.editDataModalObject)
            },
            okEdit(name) {
                var poid = localStorage.pid;
                console.log(this.formData.id);
                this.$refs[name].validate(valid => {
                    if (valid) {
                        var self = this
                        $.ajax({
                            url: " https://evp.51job.com/51job/api/51miniadmin/back.php?action=jobedit&id=" + self.editDataModalObject.id,
                            data: {
                                "jobname": self.editDataModalObject.jobname,
                                "jobareaname": self.editDataModalObject.jobareaname,
                                "degreefrom": self.editDataModalObject.degreefrom,
                                "jobnum": self.editDataModalObject.jobnum,
                                "issuedate": self.editDataModalObject.issuedate,
                                "funtype": self.editDataModalObject.funtype,
                                "content": self.editDataModalObject.content,
                                "issuedate": self.editDataModalObject.issuedate,
                                "url": self.editDataModalObject.url,
                                "divname": self.editDataModalObject.divname,
                                "jobtype": self.editDataModalObject.jobtype
                            },
                            type: "POST",
                            dataType: "json",
                            success: function(data) {
                                console.log(data);

                                if (data.code == 1) {
                                    console.log(data);
                                    self.$router.push({
                                        path: '/校招职位'
                                    })
                                    self.$Message.success('提交成功!')
                                    self.changepage(1);
                                }
                            }
                        });

                    } else {
                        this.$Message.error("编辑失败！");
                    }
                });
            },
            addNewJob() {
                this.addJobModel2 = true;
            },
            okAdd(name) {
                var poid = localStorage.pid;
                this.$refs[name].validate(valid => {
                    if (valid) {
                        var self = this
                        console.log(self.formData2.jobname)

                        $.ajax({
                            url: " https://evp.51job.com/51job/api/51miniadmin/back.php?action=jobcreate&id=" + poid + '&category=' + this.category,
                            data: {
                                "jobname": self.formData2.jobname,
                                "jobareaname": self.formData2.jobareaname,
                                "degreefrom": self.formData2.degreefrom,
                                "jobnum": self.formData2.jobnum,
                                "issuedate": self.formData2.issuedate,
                                "funtype": self.formData2.funtype,
                                "content": self.formData2.content,
                                "issuedate": self.formData2.issuedate,
                                "url": self.formData2.url,
                                "divname": self.formData2.divname,
                                "jobtype": self.formData2.jobtype
                            },
                            type: "POST",
                            dataType: "json",
                            success: function(data) {
                                console.log(data);
                                if (data.code == 1001) {
                                    self.$Message.error('职位名已经存在!')
                                }
                                if (data.code == 1) {
                                    console.log(data);
                                    self.$router.push({
                                        path: '/校招职位'
                                    })
                                    self.$Message.success('提交成功!')
                                    self.changepage(1);
                                }
                            }
                        });

                    } else {
                        this.$Message.error("添加失败");
                    }
                });
                console.log(this.formData2);
            },
            exportData() {
                this.$refs.table.exportCsv({
                    filename: "校招职位"
                });
            }
        },
        created() {
            var poid = localStorage.pid;
            console.log(localStorage.pid)
            var self = this
            $.ajax({
                url: `https://evp.51job.com/51job/api/51miniadmin/back.php?action=joblist&pagesize=20&id=${poid}&category=${this.category}`,
                type: "POST",
                dataType: "json",
                success: function(data) {

                    console.log(data);

                    if (data.data != null) {

                        self.data = data.data
                        self.jobsel = data.jobsel
                        self.pageData.total = parseInt(data.datatotal)
                        self.pageData.pageSize = 20
                        self.current = 1

                    } else {

                        self.$Message.error('没有职位');

                    }

                }
            });
            $.post('https://evp.51job.com/51job/api/1.0/index.php/mini_xy/shell/getProcessId', {
              project_id: poid
            }).then(res => {
              this.hasInternalTask = res.code === 1
            })
        }
};
</script>
<style scoped>
.modelEdit >>> .ivu-modal-footer {
    text-align: center;
}

.inline-title {
    line-height: 38px;
    text-decoration: underline;
    color: #4b80fd;
    font-family: MicrosoftYaHei;
    font-size: 14px;
}

.itemname {
    line-height: 30px;
    color: #333;
    font-size: 14px;
    font-family: MicrosoftYaHei;
}

.input-item {
    margin-left: 45px;
    width: 250px;
}

.input-item2 {
    margin-left: 45px;
    width: 275px;
}

.formitem {
    margin-left: 30px;
}
</style>
